package com.ruoyi.web.controller.common;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.NicknameUtils;
import com.ruoyi.system.domain.WfUser;
import com.ruoyi.system.domain.dto.WfDetailSaveDto;
import com.ruoyi.system.domain.dto.WfDetailUpdateDto;
import com.ruoyi.system.service.IWfDetailService;
import com.ruoyi.system.service.IWfUserService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 获取微信用户信息接口
 *
 * @author Garson
 * @date 24-08-10
 */
@RestController
@RequestMapping("/wx")
public class WxCommonController extends BaseController {

    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private IWfUserService wfUserService;
    @Autowired
    private IWfDetailService wfDetailService;

    /**
     * 通过微信code 获取微信用户信息
     */
    @GetMapping("/loginWechat")
    public AjaxResult fileDownload(@RequestParam("code") String code,
                                   @RequestParam("encryptedData") String encryptedData,
                                   @RequestParam("iv") String iv) {
        // 调用微信 API 获取用户的 openid 和 session_key
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);

            String openid = session.getOpenid();
            WfUser one = wfUserService.getOne(new LambdaQueryWrapper<WfUser>().eq(WfUser::getOpenId, openid));
            if (one != null) {
                return success().put("data", JSONUtil.toJsonStr(one));
            }
            // 调用微信 API 获取用户的手机号
            WxMaPhoneNumberInfo phoneInfo = wxMaService.getUserService().getPhoneNoInfo(session.getSessionKey(), encryptedData, iv);
            String phoneNumber = phoneInfo.getPhoneNumber();
            // 调用微信 API 获取用户的详细信息
            WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(session.getSessionKey(), encryptedData, iv);

            // 保存微信用户信息
            WfUser wfUser = new WfUser();
            wfUser.setOpenId(session.getOpenid());
            wfUser.setSessionKey(session.getSessionKey());
            wfUser.setUnionId(session.getUnionid());
            String nickName = userInfo.getNickName();
            if (StrUtil.equals("微信用户", nickName)) {
                nickName = "用户" + NicknameUtils.generateUniqueNickname();
            }
            wfUser.setNickname(nickName);
            wfUser.setAvatarUrl(userInfo.getAvatarUrl());
            wfUser.setGender(StrUtil.equals("0", userInfo.getGender()) ? 0 : 1);
            wfUser.setCountry(userInfo.getCountry());
            wfUser.setProvince(userInfo.getProvince());
            wfUser.setCity(userInfo.getCity());
            wfUser.setPhoneNumber(phoneInfo.getPhoneNumber());
            wfUserService.insertWfUser(wfUser);
            return success().put("data", JSONUtil.toJsonStr(wfUser));
        } catch (WxErrorException e) {
            logger.error("微信获取数据异常：" + e.getMessage(), e);
            return error(e.getMessage());
        }
    }

    @GetMapping("/getWechatPhone")
    public AjaxResult fileDownload(@RequestParam("code") String code,
                                   @RequestParam("openId") String openId) throws WxErrorException {
        WxMaPhoneNumberInfo newPhoneNoInfo = wxMaService.getUserService().getNewPhoneNoInfo(code);
        String phoneNumber = newPhoneNoInfo.getPhoneNumber();
        if (StrUtil.isNotBlank(phoneNumber)) {
            // 根据openId 获取对应用户，修改手机号码
            wfUserService.updateWfUserPhone(phoneNumber, openId);
        }
        return success();
    }

    @GetMapping("/getWxUserDetail")
    public AjaxResult getWxUserDetail(@RequestParam("openId") String openId) throws WxErrorException {
        WfUser wfUser = wfUserService.selectWfUserByOpenId(openId);
        return success().put("data", JSONUtil.toJsonStr(wfUser));
    }

    /**
     * 获取WIFI信息详细信息
     */
    @GetMapping(value = "/getWifiDetail")
    public AjaxResult getInfo(@RequestParam("wfId") Long wfId) {
        return success(wfDetailService.getById(wfId));
    }

    /**
     * 获取WIFI信息列表
     */
    @GetMapping(value = "/getWifiListByUnionId")
    public AjaxResult getWifiListByUnionId(@RequestParam("openId") String openId) {
        return success(wfDetailService.getWifiListByUnionId(openId));
    }

    /**
     * 新增WIFI信息
     */
    @PostMapping(value = "/saveWifi")
    public AjaxResult add(@Validated @RequestBody WfDetailSaveDto saveDto) {
        wfDetailService.saveWf(saveDto);
        return success();
    }

    /**
     * 修改WIFI信息
     */
    @PutMapping(value = "updateWifi")
    public AjaxResult edit(@Validated @RequestBody WfDetailUpdateDto updateDto) {
        wfDetailService.updateWfById(updateDto);
        return success();
    }

    @DeleteMapping("deleteWifi")
    public AjaxResult remove(@RequestParam("wfId") String wfId, @RequestParam("openId") String openId) {
        return toAjax(wfDetailService.deleteWifi(wfId, openId));
    }

}
